package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Mylinja 2021-12-17 星期五 18:12
 */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishFlavorService dishFlavorService;

    /**
     * 新增菜品方法
     *
     * @param dishDto 菜品dto都西昂
     * @return 返回结果
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info("新增菜品...");
        log.info("菜品为：{}", dishDto);

        dishService.saveWithFlavor(dishDto);
        return R.success("添加菜品成功");
    }

    /**
     * 分页查询所有菜品方法
     *
     * @param page     页码
     * @param pageSize 每页条目
     * @param name     查询条件
     * @return 返回page对象
     */
    @GetMapping("/page")
    @SuppressWarnings({"unchecked", "varargs"})
    public R<Page<DishDto>> page(int page, int pageSize, String name) {
        log.info("page = {},pageSize = {},name = {}", page, pageSize, name);

        //1). 构造分页条件对象
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        Page<DishDto> dishDtoInfo = new Page<>();

        //2). 构建查询及排序条件
        LambdaQueryWrapper<Dish> query = new LambdaQueryWrapper<>();
        query.like(name != null, Dish::getName, name);
        query.orderByDesc(Dish::getUpdateTime);

        //3). 执行分页条件查询
        dishService.page(pageInfo, query);

        //4). 遍历分页查询列表数据，根据分类ID查询分类信息，从而获取该菜品的分类名称
        // 拷贝对象，从pageInfo拷贝到dishDtoInfo中，并且忽略records属性不拷贝
        BeanUtils.copyProperties(pageInfo, dishDtoInfo, "records");
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> list = records.stream().map((item) -> {
            //4.1 开启流管道，把records放入流中进行处理，把Dish对象拷贝给DishDto对象
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);

            //4.2 得到每个Dish对象的categoryId分类id
            Long categoryId = item.getCategoryId();

            //4.3 根据categoryId，先查一下Category对象是否存在
            Category byId = categoryService.getById(categoryId);
            if (byId != null) {
                //4.4 设置每个DishDto对象的分类名称
                dishDto.setCategoryName(byId.getName());
            }
            return dishDto;
        }).collect(Collectors.toList());

        //5). 把DishDto集合，封装到page对象中的records属性中，并返回
        dishDtoInfo.setRecords(list);
        return R.success(dishDtoInfo);
    }

    /**
     * 菜品信息回显
     *
     * @param id 根据id查询菜品信息
     * @return 返回菜品
     */
    @GetMapping("/{id}")
    public R<DishDto> echoDtoInfo(@PathVariable long id) {
        log.info("开始回显菜品信息...");

        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 修改菜品信息
     *
     * @param dishDto 菜品dto对象
     * @return 返回结果
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        log.info("执行更新菜品方法...");

        dishService.updateByIdWithFlavor(dishDto);
        return R.success("修改成功");
    }

    /**
     * 批量删除菜品
     *
     * @param ids 删除菜品的ids
     */
    @DeleteMapping
    public R<String> deleteDish(@RequestParam List<Long> ids) {
        log.info("删除菜品...");
        dishService.deleteByIds(ids);
        return R.success("删除成功");
    }

    /**
     * 根据分类id，查询此分类下的所有菜品
     *
     * @param dish 分类id
     * @return 返回菜品集合
     */
    @GetMapping("/list")
    @SuppressWarnings({"unchecked", "varargs"})
    public R<List<DishDto>> selectList(Dish dish) {
        log.info("查询所有菜品...");

        // 查询此分类下的所有菜品
        LambdaQueryWrapper<Dish> query = new LambdaQueryWrapper<>();
        query.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        // 只有起售状态的才展示
        query.eq(Dish::getStatus, 1);
        query.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(query);

        List<DishDto> records = list.stream().map((dishInList) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dishInList, dishDto);

            Long dishInListId = dishInList.getId();
            // 查询菜品口味表  SQL: select * from dish_flavor where dish_id = ?
            LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(DishFlavor::getDishId, dishInListId);
            List<DishFlavor> list1 = dishFlavorService.list(queryWrapper);
            dishDto.setFlavors(list1);
            return dishDto;
        }).collect(Collectors.toList());
        return R.success(records);
    }

    /**
     * 修改菜品状态
     *
     * @param state 状态码
     * @param ids   菜品集合
     * @return 返回结果
     */
    @PostMapping("/status/{state}")
    public R<String> status(@PathVariable Integer state, @RequestParam List<Long> ids) {
        log.info("批量修改菜品状态。。。");

        //1 根据ids修改菜品状态
        //SQL: update from dish set(status) value(0) where id in(ids)
        LambdaUpdateWrapper<Dish> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(Dish::getId, ids);
        updateWrapper.set(Dish::getStatus, state);
        dishService.update(updateWrapper);

        return R.success("更新成功");
    }

}
